// DDNS-Go 前端脚本
class DDNSFrontend {
    constructor() {
        this.apiUrl = '/api/domains';
        this.init();
    }

    init() {
        // 页面加载完成后自动获取域名列表
        document.addEventListener('DOMContentLoaded', () => {
            this.loadDomainList();
        });
    }

    async loadDomainList() {
        console.log('开始加载域名列表');
        this.showLoading();
        this.hideError();
        this.hideDomainList();
        this.hideStats();

        try {
            console.log(`准备发送API请求到: ${this.apiUrl}`);
            console.log('API请求参数:', { method: 'GET', url: this.apiUrl });
            
            const startTime = Date.now();
            const response = await fetch(this.apiUrl);
            const endTime = Date.now();
            
            console.log(`API请求完成，耗时: ${endTime - startTime}ms`);
            console.log('API响应状态:', response.status, response.statusText);
            console.log('API响应头:', Object.fromEntries(response.headers.entries()));
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            console.log('API响应数据:', data);
            
            this.displayDomainList(data);
            this.updateStats(data);
            this.updateLastUpdateTime();
            
        } catch (error) {
            console.error('获取域名列表失败:', error);
            console.error('错误详情:', error.message, error.stack);
            this.showError('无法连接到服务器，请检查DDNS-Go服务是否正在运行');
        }
        console.log('域名列表加载流程结束');
    }

    displayDomainList(data) {
        console.log('显示域名列表，数据:', data);
        const listContainer = document.getElementById('list-items');
        listContainer.innerHTML = '';

        if (!data || !data.domains || !Array.isArray(data.domains) || data.domains.length === 0) {
            console.log('没有有效的域名数据');
            listContainer.innerHTML = `
                <div class="domain-item" style="text-align: center; grid-template-columns: 1fr;">
                    <span>暂无域名解析记录</span>
                </div>
            `;
            this.showDomainList();
            this.hideLoading();
            return;
        }

        console.log(`处理${data.domains.length}个域名项`);
        data.domains.forEach((domain, index) => {
            if (!domain) {
                console.warn(`域名项${index}为空，跳过`);
                return;
            }
            try {
                const domainItem = this.createDomainItem(domain);
                listContainer.appendChild(domainItem);
            } catch (error) {
                console.error(`处理域名项${index}失败:`, error, domain);
            }
        });

        this.showDomainList();
        this.hideLoading();
    }

    createDomainItem(domain) {
        console.log('处理域名项:', domain);
        const item = document.createElement('div');
        
        // 兼容大小写字段名，优先使用后端返回的大写字段
        const domainType = domain.Type || domain.type || '未知';
        item.className = `domain-item ${domainType.toLowerCase()}`;
        
        // 兼容sub和domain字段（后端返回的是Sub）
        const sub = domain.Sub || domain.sub || '';
        // 注意：后端数据中没有domain字段，只有Sub字段，使用默认域名
        const domainName = 'liumou.site'; // 根据日志中的实际域名设置
        const fullDomain = sub ? `${sub}.${domainName}` : domainName;
        
        // 后端数据中没有status字段，默认显示为正常
        const statusClass = 'active';
        const statusText = '正常';
        
        // 兼容ip字段（后端返回的是Ip）
        const ip = domain.Ip || domain.ip || '未知IP';
        
        item.innerHTML = `
            <span class="domain-name" title="${fullDomain}">${fullDomain}</span>
            <span class="record-type">${domainType}</span>
            <span class="ip-address" title="${ip}">${ip}</span>
            <span class="status ${statusClass}">${statusText}</span>
        `;

        return item;
    }

    updateStats(data) {
        if (!data || !data.domains) {
            document.getElementById('total-count').textContent = '0';
            document.getElementById('ipv4-count').textContent = '0';
            document.getElementById('ipv6-count').textContent = '0';
            return;
        }

        const domains = data.domains;
        const totalCount = domains.length;
        const ipv4Count = domains.filter(d => d.type === 'A').length;
        const ipv6Count = domains.filter(d => d.type === 'AAAA').length;

        document.getElementById('total-count').textContent = totalCount;
        document.getElementById('ipv4-count').textContent = ipv4Count;
        document.getElementById('ipv6-count').textContent = ipv6Count;

        this.showStats();
    }

    updateLastUpdateTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        document.getElementById('last-update').textContent = timeString;
    }

    showLoading() {
        document.getElementById('loading').style.display = 'block';
    }

    hideLoading() {
        document.getElementById('loading').style.display = 'none';
    }

    showError(message) {
        const errorElement = document.getElementById('error');
        const errorMessage = document.getElementById('error-message');
        errorMessage.textContent = message;
        errorElement.style.display = 'block';
        this.hideLoading();
    }

    hideError() {
        document.getElementById('error').style.display = 'none';
    }

    showDomainList() {
        document.getElementById('domain-list').style.display = 'block';
    }

    hideDomainList() {
        document.getElementById('domain-list').style.display = 'none';
    }

    showStats() {
        document.getElementById('stats').style.display = 'flex';
    }

    hideStats() {
        document.getElementById('stats').style.display = 'none';
    }
}

// 全局函数供HTML调用
function loadDomainList() {
    console.log('全局函数loadDomainList被调用');
    if (!window.ddnsFrontend) {
        console.log('ddnsFrontend实例不存在，创建新实例');
        window.ddnsFrontend = new DDNSFrontend();
    } else {
        console.log('使用已存在的ddnsFrontend实例');
        window.ddnsFrontend.loadDomainList();
    }
}

// 自动刷新功能（可选）
function startAutoRefresh(interval = 30000) { // 默认30秒刷新一次
    setInterval(() => {
        if (window.ddnsFrontend) {
            window.ddnsFrontend.loadDomainList();
        }
    }, interval);
}

// 初始化应用
window.addEventListener('load', () => {
    console.log('窗口加载完成，开始初始化DDNS前端应用');
    window.ddnsFrontend = new DDNSFrontend();
    
    // 添加额外的错误监听
    window.addEventListener('error', (event) => {
        console.error('窗口错误:', event.error, event.message, event.filename, event.lineno);
    });
    
    // 开启自动刷新以便测试
    console.log('开启自动刷新功能，每10秒刷新一次');
    startAutoRefresh(10000);
});